# -*- coding:utf-8 -*-
"""
本脚本用来管理 渲染层的创建与通道层的设置
"""

import sys
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
try:

    import maya.cmds as cmds
    import maya.mel as mel
    from maya import OpenMayaUI as omui
    from shiboken2 import wrapInstance
    import mtoa.aovs as aovs
except Exception as import_err:
    print('test')

def maya_main_window():
    """
     Return the Maya main window widget as a Python object
    :return:
    """
    main_window_ptr = omui.MQtUtil.mainWindow()
    return wrapInstance(long(main_window_ptr), QWidget)



class AovWidget(QWidget):

    def __init__(self):
        super(AovWidget, self).__init__()

        self.main_layout = QHBoxLayout()
        self.main_layout.setSpacing(10)
        self.aov_label = QLabel('AOV:')
        self.aov_edit = QLineEdit()
        self.aov_edit.setFixedWidth(120)
        self.aov_type_comb = QComboBox()
        self.init_aov_type()
        self.main_layout.addWidget(self.aov_label)
        self.main_layout.addWidget(self.aov_edit)
        self.main_layout.addWidget(self.aov_type_comb)
        self.setLayout(self.main_layout)


    def init_aov_type(self):
        aov_type_list = ['rgba','rgb','vector']
        self.aov_type_comb.addItems(aov_type_list)

    def get_aov(self):
        aov_name = self.aov_edit.text()
        aov_type = self.aov_type_comb.currentText()

        if aov_name:
            return {aov_name:aov_type}
        else:
            return None


class AovList(QListWidget):

    def __init__(self):
        super(AovList, self).__init__()

        self.setContextMenuPolicy(Qt.CustomContextMenu)  # 开启自定义右击菜单
        self.customContextMenuRequested.connect(self.right_menu)
        self.setSelectionMode(QAbstractItemView.ExtendedSelection)

    def right_menu(self):
        rMenu = QMenu()

        addAction = QAction(u'新增',self)
        addAction.triggered.connect(self._add_aov)
        rMenu.addAction(addAction)
        delAction = QAction(u'删除', self)
        delAction.triggered.connect(self._delete_aov)
        rMenu.addAction(delAction)
        saveAction = QAction(u'保存',self)
        saveAction.triggered.connect(self._delete_aov)
        rMenu.addAction(saveAction)
        rMenu.exec_(QCursor.pos())


    def _add_aov(self):
        item = QListWidgetItem()  # 创建QListWidgetItem对象
        item.setSizeHint(QSize(200, 50))  # 设置QListWidgetItem大小
        aw = AovWidget()  # 调用上面的函数获取对应
        self.addItem(item)  # 先添加item
        self.setItemWidget(item, aw)

    def _delete_aov(self):
        pass



class LightLayerWindow(QWidget):

    def __init__(self,parent):
        super(LightLayerWindow, self).__init__(parent)
        self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.Window)
        self.big_font = QFont('',14,65)
        self.mid_font = QFont('',11,65)
        self.resize(400,300)
        self.setWindowTitle(u'渲染层管理')
        self.main_layout = QVBoxLayout()
        self.main_layout.setSpacing(15)
        self.main_layout.setAlignment(Qt.AlignTop)
        self.tool_name = QLabel(u'渲染层管理')
        self.tool_name.setFont(self.big_font)
        self.tool_name.setAlignment(Qt.AlignCenter)
        self.layer_layout = QHBoxLayout()
        self.layer_edit = QLineEdit()
        self.layer_btn = QPushButton(u'创建层')
        self.layer_btn.clicked.connect(self._create_layer)
        self.update_btn = QPushButton(u'独立各层AOV')
        self.update_btn.clicked.connect(self._update_layer)
        self.layer_layout.addWidget(self.layer_edit)
        self.layer_layout.addWidget(self.layer_btn)
        self.layer_layout.addWidget(self.update_btn)
        self.tip_label = QLabel(u'注意：必须开启Legacy Render Layers模式！')
        self.tip_label.setContentsMargins(0,40,0,0)
        self.main_layout.addWidget(self.tool_name)
        self.main_layout.addLayout(self.layer_layout)
        self.main_layout.addWidget(self.tip_label)
        self.setLayout(self.main_layout)
        

    def get_layer_name(self,name):

        layers = cmds.ls(type="renderLayer")
        if name in layers:
            new_name = ''
            last_char = name[-1]
            try:
                num = int(last_char)
                new_num = num+1
                new_name = name + str(new_num)
            except :
                new_name = name + '1'
            return new_name
        else:
            return name


    def _create_layer(self):
        layer_name = self.layer_edit.text()
        if not layer_name:
            return
        layer_name = self.get_layer_name(layer_name)

        cmds.createRenderLayer(name=layer_name, mc=True, nr=True)
        try:
            cmds.editRenderLayerAdjustment("defaultArnoldRenderOptions.AASamples", layer=layer_name)
            cmds.editRenderLayerAdjustment("defaultArnoldRenderOptions.AASamples", layer=layer_name)
            cmds.setAttr("defaultArnoldRenderOptions.AASamples", 3)
            cmds.editRenderLayerAdjustment("defaultArnoldRenderOptions.GIDiffuseSamples", layer=layer_name)
            cmds.setAttr("defaultArnoldRenderOptions.GIDiffuseSamples", 1)
            cmds.editRenderLayerAdjustment("defaultArnoldRenderOptions.GISpecularSamples", layer=layer_name)
            cmds.setAttr("defaultArnoldRenderOptions.GISpecularSamples", 3)
            cmds.editRenderLayerAdjustment("defaultArnoldRenderOptions.GITransmissionSamples", layer=layer_name)
            cmds.setAttr("defaultArnoldRenderOptions.GITransmissionSamples", 1)
            cmds.editRenderLayerAdjustment("defaultArnoldRenderOptions.GISssSamples", layer=layer_name)
            cmds.setAttr("defaultArnoldRenderOptions.GISssSamples", 1)
            cmds.editRenderLayerAdjustment("defaultArnoldRenderOptions.GIVolumeSamples", layer=layer_name)
            cmds.setAttr("defaultArnoldRenderOptions.GIVolumeSamples", 1)
            cmds.editRenderLayerAdjustment("defaultArnoldRenderOptions.aovMode", layer=layer_name)
            cmds.setAttr("defaultArnoldRenderOptions.aovMode", 1)
            cmds.editRenderLayerAdjustment("aiAOV_specular_direct.enabled", layer=layer_name)
            cmds.setAttr("aiAOV_specular_direct.enabled", 1)
            cmds.editRenderLayerAdjustment("aiAOV_specular_indirect.enabled", layer=layer_name)
            cmds.setAttr("aiAOV_specular_indirect.enabled", 1)
            cmds.editRenderLayerAdjustment("aiAOV_RGBA.lightGroups")
            cmds.setAttr("aiAOV_RGBA.lightGroups", 0)
        except :
            pass
        sceneAOVs = aovs.AOVInterface().getAOVNodes(names=True)
        for i in sceneAOVs:
            cmds.editRenderLayerAdjustment(i[1] + ".enabled", layer=layer_name)

        QMessageBox.information(None,u"提示",'{}创建成功'.format(layer_name))

    def _update_layer(self):
        sceneAOVs = aovs.AOVInterface().getAOVNodes(names=True)
        for lay in cmds.ls(type="renderLayer"):
            if lay != 'defaultRenderLayer':
                for i in sceneAOVs:
                    cmds.editRenderLayerAdjustment(i[1] + ".enabled", layer=lay)

        QMessageBox.information(None,u"提示",'独立各层aov完成')


def _run():
    try:
        dialog.show()
        dialog.setHidden(False)
    except :

        dialog = LightLayerWindow(parent=maya_main_window())
        dialog.show()

def _doc():
    doc = {'name':u'渲染层管理','doc':u'管理渲染层'}
    return doc


if __name__ == '__main__':
    app = QApplication(sys.argv)
    l = LightLayerWindow(None)
    # l = AovWidget()
    # l = AovList()
    l.show()
    sys.exit(app.exec_())
        
        
